<template>
	<div>
		<use-table ref="tbl"></use-table>
		<div class="container_status dflex_vertical_c">
			<div class="item_interval" v-for="(item, i) in stateDatas" :key="i">
				<el-button class="badge_txt" :class="{ active: item.name == state }" size="small" @click="cutSta(item)">
					{{ item.name }}
				</el-button>
				<v-countup class="badge" start-value="0" :end-value="item.cnt"></v-countup>
			</div>
		</div>
		<div class="container padding_b_0">
			<div class="dflex_wrap">
				<div class="dflex_vertical_c margin_r_40 margin_b_20">
					<div class="search_name">兑换码：</div>
					<el-input v-model="req.code" placeholder="请输入" class="search_input" @change="search" clearable>
					</el-input>
				</div>
				<el-button size="mini" :loading="searchBtnLoading" class="search-btn margin_b_20 margin_r_40"
					@click="search">搜索</el-button>
			</div>
		</div>
		<div class="container last_container use-table">
			<div class="dflex_sb margin_b_15 table-head">
				<el-button class="batch-btn padding0" :loading="removesBtnLoading" @click="removes">删除<span
						v-if="selectDatas.length">×{{selectDatas.length}}</span></el-button>
				<el-button round icon="el-icon-back" class="return-btn" @click="returnPage">返回</el-button>
			</div>
			<el-table ref="etbl" :height="tblHeight" v-loading="tableLoading" :data="tableDatas" highlight-current-row
				style="width: 100%" @selection-change="selectionChange">
				<el-table-column type="selection" :selectable="selectable"></el-table-column>
				<el-table-column label="用户" width="200" align="center">
					<template slot-scope="scope">
						<div class="dflex_vertical_c">
							<el-image class="headimg_small"
								:src="scope.row.member_headimg || 'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png'"
								:preview-src-list="scope.row.previewImgs" fit="cover"></el-image>
							<div class="margin_l_5">{{ scope.row.member_name || '--' }}</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column property="code" label="兑换码" align="center"></el-table-column>
				<el-table-column property="name" label="名称" align="center"></el-table-column>
				<el-table-column property="member_type" label="用户类型" align="center"></el-table-column>
				<el-table-column label="面值" align="center">
					<template slot-scope="scope">
						<div>{{ scope.row.price / 100 }}{{ scope.row.type == '满减' ? '元' : '折' }}</div>
					</template>
				</el-table-column>
				<el-table-column label="消费满减" align="center">
					<template slot-scope="scope">
						<div v-if="scope.row.order_amount == 0">不限</div>
						<div v-else>{{ scope.row.order_amount }} 元</div>
					</template>
				</el-table-column>
				<el-table-column property="receive_type" label="领取方式" align="center"></el-table-column>
				<el-table-column property="end_time" label="过期时间" align="center" width="220"></el-table-column>
				<el-table-column property="state" label="状态" align="center"></el-table-column>
				<el-table-column label="操作" align="center" width="120" fixed="right">
					<template slot-scope="scope">
						<el-popover placement="left" trigger="hover" :open-delay="0" :close-delay="50"
							@show="preview(scope.row)">
							<image :src="posterUrl" style="width: 200px;height: 200px;" />
							<div class="dflex_level_c w100">
								<el-tooltip :open-delay="350" content="下载" placement="top" :hide-after="1000"
									:enterable="false" effect="light">
									<el-button circle size="medium" class="coupon_download pos_r table-btn"
										icon="el-icon-download">
										<a class="pos_a" :href="posterUrl" :download="scope.row.code"></a>
									</el-button>
								</el-tooltip>
							</div>
							<el-tooltip v-if="scope.row.state == '待领取'" slot="reference" :open-delay="350" content="二维码"
								placement="top" :hide-after="1000" :enterable="false" effect="light">
								<el-button circle size="medium" icon="el-icon-view" class="table-btn">
								</el-button>
							</el-tooltip>
						</el-popover>
						<el-tooltip v-if="scope.row.state == '待领取'" :open-delay="350" content="删除" placement="top"
							:hide-after="1000" :enterable="false" effect="light">
							<el-button circle size="medium" icon="el-icon-delete" class="margin_l_10 table-btn"
								@click="remove(scope.row._id)"></el-button>
						</el-tooltip>
					</template>
				</el-table-column>
				<div slot="empty">
					<el-empty description=" "></el-empty>
				</div>
			</el-table>
			<el-pagination background :current-page="req.page" :page-sizes="[10, 20, 30, 50, 100]" :page-size="req.rows"
				layout="total, sizes, prev, pager, next, jumper" :total="tableTotal" @size-change="sizeChange"
				@current-change="currentChange" class="page"></el-pagination>
		</div>
		<!-- 海报 -->
		<view v-if="posterShow" class="pos_a" style="left: -9999px;">
			<l-painter :board="posterData" isRenderImage @success="posterSuccess" />
		</view>
	</div>
</template>

<script>
	import lPainter from '@/uni_modules/lime-painter/components/lime-painter/';
	import uposter from '@/common/poster.js';
	import QRCode from 'qrcode';
	import vCountup from 'vue-countupjs';
	const __name = 'wmzmall-marketing-coupon';
	export default {
		components: {
			vCountup,
			lPainter
		},
		data() {
			return {
				state: '全部',
				stateObj: {
					待领取: 0,
					已领取: 0,
					已使用: 0,
					已过期: 0,
					全部: 0
				},
				stateDatas: [],
				dataId: '',
				req: {
					page: 1,
					rows: 100,
					orderby: 'create_time asc',
					code: '',
					state: ''
				},
				tblHeight: 0,
				tableLoading: false,
				tableDatas: [],
				tableTotal: 0,
				posterShow: false,
				posterData: {},
				couponData: {},
				posterUrl: '',
				selectDatas: [],
				searchBtnLoading: false,
				removesBtnLoading: false
			};
		},
		methods: {
			async loadData(callback) {
				this.tableLoading = true;

				this.stateDatas = [];
				for (let key in this.stateObj) {
					this.stateDatas.push({
						name: key,
						cnt: this.stateObj[key]
					});
				}

				await this.$db[__name]
					.noshopid()
					.whereif(this.req.state && this.req.state != '全部', {
						state: this.req.state
					})
					.whereif(this.req.code, {
						code: new RegExp(this.$api.filterRegexpKey(this.req.code), 'i')
					})
					.where({
						coupon_id: this.dataId
					})
					.withgroup({
						field: 'state',
						obj: this.stateObj
					})
					.totable(this.req)
					.then(res => {
						if (res.code == 200) {
							if (res.datas.group && res.datas.group.datas) {
								this.stateDatas = res.datas.group.datas;
							}

							res.datas.rows.forEach((row, idx) => {
								row.previewImgs = [(row.member_headimg && row.member_headimg.replace(
										"/132", "/0")) ||
									'https://7463-tcb-rflrz31u8yan4rr9ad60d-268679-1308293149.tcb.qcloud.la/1659579992133_0.png'
								];
								row.end_time = new Date(row.end_time).format();
							});

							this.tableDatas = res.datas.rows;
							this.tableTotal = res.datas.total;

							if (typeof callback === 'function') {
								callback();
							}
						}
						this.searchBtnLoading = false;
						this.tableLoading = false;
					});
			},
			search() {
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.searchBtnLoading = true;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});

				uni.setStorage({
					key: '__search' + this.$route.path,
					data: this.req
				});
			},
			preview(row) {
				this.posterShow = true;
				this.couponData = row;
				this.creatQrCode(`${row.code}`);
			},
			creatQrCode(url) {
				QRCode.toDataURL(url, {
					width: 200,
					margin: 0,
					errorCorrectionLevel: 'H'
				}, (err, base64Url) => {
					this.posterData = uposter.getPosterData(this.couponData, base64Url);
				});
			},
			posterSuccess(res) {
				var blob = this.getBlob(res);
				this.posterUrl = window.URL.createObjectURL(blob);
				this.posterShow = false;
			},
			getBlob(base64) {
				let mimeString = base64
					.split(',')[0]
					.split(':')[1]
					.split(';')[0]; // mime类型
				let byteString = atob(base64.split(',')[1]); //base64 解码
				let arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
				let intArray = new Uint8Array(arrayBuffer); //创建视图
				for (let i = 0; i < byteString.length; i += 1) {
					intArray[i] = byteString.charCodeAt(i);
				}
				return new Blob([intArray], {
					type: mimeString
				});
			},
			remove(id) {
				this.$confirm('此操作将删除该优惠券!', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$func.wmzadmin.call('coupon/remove', {
						ids: [id],
						couponId: this.dataId
					}).then(res => {
						if (res.code == 200) {
							this.loadData();
						}
					});
				});
			},
			selectionChange(datas) {
				this.selectDatas = datas;
			},
			selectable(datas) {
				if (datas.state == '待领取') {
					return true;
				}

				return false;
			},
			removes() {
				if (this.selectDatas.length <= 0) {
					this.$message('请勾选需要删除的数据！');
					return;
				}

				let ids = this.selectDatas.map(x => x._id);

				this.$confirm('此操作将永久删除勾选数据！', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.removesBtnLoading = true;
					this.$func.wmzadmin.call('coupon/remove', {
						ids: ids,
						couponId: this.dataId
					}).then(res => {
						if (res.code == 200) {
							this.loadData();
						}
						this.removesBtnLoading = false;
					});
				});
			},
			cutSta(item) {
				uni.setStorage({
					key: '__tabs' + this.$route.path,
					data: item
				});

				this.state = item.name;
				this.req.state = item.name;
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			sizeChange(size) {
				this.$api.storagePaginationRows(size, this.$route.path);
				this.req.page = 1;
				this.$api.storagePaginationPage(this.req.page, this.$route.path);
				this.req.rows = size;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			currentChange(current) {
				this.$api.storagePaginationPage(current, this.$route.path);
				this.req.page = current;

				this.loadData(() => {
					this.$refs.etbl.bodyWrapper.scrollTop = 0;
				});
			},
			returnPage() {
				uni.$emit('closeTab');
				uni.redirectTo({
					url: '/pages/marketing/coupon/coupon'
				});
			}
		},
		created() {
			let __search = uni.getStorageSync('__search' + this.$route.path);
			if (__search) {
				this.req = __search;
			}

			this.dataId = this.$route.query.id || '';

			let thisCutSta = uni.getStorageSync('__tabs' + this.$route.path);
			this.state = '全部';
			this.req.page = 1;
			this.req.state = this.state;
			if (thisCutSta) {
				this.state = thisCutSta.name;
				this.req.state = thisCutSta.name;
			}
			this.req.page = uni.getStorageSync('__paginationPage' + this.$route.path) || 1;
			this.req.rows = uni.getStorageSync('__paginationRows' + this.$route.path) || 10;

			this.loadData(() => {
				this.$nextTick(() => {
					this.$api.scrollToStorage('.el-table__body-wrapper', this.$route.path);
				});
			});
		},
		mounted() {
			this.$nextTick(() => {
				this.$api.scrollOnStorage('.el-table__body-wrapper', this.$route.path);
			});
		},
		updated() {
			if (!this.tblHeight) {
				this.tblHeight = this.$refs.tbl.tblHeight;
			}
		}
	};
</script>

<style>
	.coupon_download>>>span {
		margin: 0;
	}

	.coupon_download a {
		left: 0;
		top: 0;
		right: 0;
		bottom: 0;
	}
</style>
